package com.example.choupaiapp.main.activity.home;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.example.choupaiapp.R;
import com.example.choupaiapp.common.adapter.BaseAdapterHelper;
import com.example.choupaiapp.common.adapter.QuickAdapter;
import com.example.choupaiapp.common.ui.activity.CommonActivity;
import com.example.choupaiapp.common.util.Utils;
import com.example.choupaiapp.main.bean.HomeLocationBean;
import com.example.choupaiapp.main.bean.PublishLocationBean;
import com.example.choupaiapp.main.bean.PublishMapLocationBean;
import com.example.choupaiapp.main.util.LocationUtil;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by ASUS on 2019/11/28.
 */

public class SearchLocationActivity extends CommonActivity implements PoiSearch.OnPoiSearchListener, OnRefreshLoadMoreListener {

    @BindView(R.id.search_et)
    EditText searchEt;
    @BindView(R.id.clear)
    ImageView clear;
    @BindView(R.id.listview)
    ListView listview;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    private String citycode;
    private double lat;
    private double lot;
    private int pageSize = 20;
    private int pageNum = 1;
    private QuickAdapter<PoiItem> quickAdapter;
    private String flag;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_location);
    }

    private void setSoftKeyboard(EditText editText) {
        editText.setFocusable(true);
        editText.setFocusableInTouchMode(true);
        editText.requestFocus();

        //为 commentEditText 设置监听器，在 DialogFragment 绘制完后立即呼出软键盘，呼出成功后即注销
        editText.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (inputMethodManager != null) {
                    if (inputMethodManager.showSoftInput(editText, 0)) {
                        editText.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                    }
                }
            }
        });
    }

    @Override
    protected void initView() {

        refreshLayout.setOnRefreshLoadMoreListener(this);
        refreshLayout.setRefreshHeader(new MaterialHeader(context).setColorSchemeResources(R.color.common_color));

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            citycode = bundle.getString("citycode");
            flag = bundle.getString("flag");
            lat = bundle.getDouble("lat");
            lot = bundle.getDouble("lot");
        }

        searchEt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    if (!TextUtils.isEmpty(searchEt.getText().toString().trim())) {
                        //点击搜索的时候隐藏软键盘
                        InputMethodManager manager = (InputMethodManager) searchEt.getContext()
                                .getSystemService(Context.INPUT_METHOD_SERVICE);
                        manager.hideSoftInputFromWindow(searchEt.getWindowToken(), 0);
                        // 在这里写搜索的操作,一般都是网络请求数据
                        pageNum = 1;
                        LocationUtil.getInstance().searchPoiOption(searchEt.getText().toString().trim(), citycode, SearchLocationActivity.this, 0, 0, 0);
                        LocationUtil.getInstance().setQuery(pageNum++, pageSize);
                        LocationUtil.getInstance().searchPoi();
                    }
                    return true;
                }

                return false;
            }
        });

        quickAdapter = new QuickAdapter<PoiItem>(context, R.layout.item_loaction) {
            @Override
            protected void convert(BaseAdapterHelper helper, PoiItem item) {
                helper.setText(R.id.location, item.getTitle());
                helper.setText(R.id.address, item.getSnippet());
            }
        };

        listview.setAdapter(quickAdapter);

        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if ("home".equals(flag)) {
                    HomeLocationBean homeLocationBean = new HomeLocationBean();
                    homeLocationBean.setItem(quickAdapter.getItem(i));
                    EventBus.getDefault().post(homeLocationBean);
                } else if ("publish".equals(flag)) {
                    PublishLocationBean publishLocationBean = new PublishLocationBean();
                    publishLocationBean.setItem(quickAdapter.getItem(i));
                    EventBus.getDefault().post(publishLocationBean);
                }else if("publish_map".equals(flag)){
                    PublishMapLocationBean publishMapLocationBean = new PublishMapLocationBean();
                    publishMapLocationBean.setPoiItem(quickAdapter.getItem(i));
                    EventBus.getDefault().post(publishMapLocationBean);
                }
                finishActivity();
            }
        });

        setSoftKeyboard(searchEt);
    }

    @Override
    protected void initData() {

    }

    @OnClick({R.id.clear, R.id.cancel})
    public void onViewClicked(View view) {
        if (Utils.isDoubleClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.clear:
                searchEt.setText("");
                break;
            case R.id.cancel:
                finishActivity();
                break;
        }
    }

    @Override
    public void onPoiSearched(PoiResult poiResult, int i) {
        if (i == 1000 && poiResult != null && poiResult.getPois().size() > 0) {
            if (pageNum == 2) {
                quickAdapter.clear();
            }
            quickAdapter.addAll(poiResult.getPois());
            quickAdapter.notifyDataSetChanged();
            refreshLayout.finishRefresh();
            refreshLayout.finishLoadMore();
        } else {
            refreshLayout.finishRefresh();
            refreshLayout.finishLoadMore();
//            showImageToas("附近暂无数据");
        }
    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {

    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        if(LocationUtil.getInstance().getQuery()==null){
            LocationUtil.getInstance().searchPoiOption(searchEt.getText().toString().trim(), citycode, SearchLocationActivity.this, 0, 0, 0);
        }
        LocationUtil.getInstance().setQuery(pageNum++, pageSize);
        LocationUtil.getInstance().searchPoi();
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        pageNum = 1;
        if(LocationUtil.getInstance().getQuery()==null){
            LocationUtil.getInstance().searchPoiOption(searchEt.getText().toString().trim(), citycode, SearchLocationActivity.this, 0, 0, 0);
        }
        LocationUtil.getInstance().setQuery(pageNum++, pageSize);
        LocationUtil.getInstance().searchPoi();
    }

}
